package com.atom.common.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.atom.common.CommentFlowStatus;
import com.atom.common.entity.CommentFlowDO;
import com.atom.common.exception.AvensNullPointerException;
import com.atom.common.util.CommonUserResolver;

@Repository
public class CommentFlowDao extends AvensCommonDao<CommentFlowDO> {
  
  @Resource CommonUserResolver commonUserResolver;

  public List<CommentFlowDO> findByMainPrcInsIdByTaskDefKey(String mainProcessInstanceId, String taskDefinitionKey) {
    Map<String, Object> var = new HashMap<String, Object>();
    var.put("mainProcessInstanceId", mainProcessInstanceId);
    var.put("taskDefinitionKey", taskDefinitionKey);
    return super.findByProperties(var);
  }
  
  public void saveCommentFlow(List<String> users, String processInstanceId, String nextTaskDefinitionKey, String creator) {
    for (String user : users) {
      CommentFlowDO entity = new CommentFlowDO();
      entity.setAssignee(user);
      entity.setAssigneeText(commonUserResolver.getUserNameByUserId(user));
      entity.setCreator(creator);
      entity.setMainProcessInstanceId(processInstanceId);
      entity.setStatus(CommentFlowStatus.DOING);
      entity.setTaskDefinitionKey(nextTaskDefinitionKey);
      super.save(entity);
    }      
  }
  
  public void updateCommentFlowStatus(String mainProcessInstanceId, String taskDefinitionKey, String assignee, String creator, int status) {
    Map<String, Object> var = new HashMap<String, Object>(); 
    var.put("mainProcessInstanceId", mainProcessInstanceId);
    var.put("taskDefinitionKey", taskDefinitionKey);
    var.put("assignee", assignee);
    var.put("creator", creator);
    List<CommentFlowDO> list = super.findByProperties(var);
    if (list == null || list.size() == 0) {
      throw new AvensNullPointerException("UPDATE CommentFlow Status IS NULL");
    }
    CommentFlowDO entity = list.get(0);
    entity.setStatus(status);
    super.update(entity);
  }

}
